package ypmits.cms.view.windows {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Timer;

	/**
	 * @author Dave Lenz
	 */
	public class SectionChooser extends Sprite {
		
		private static var _instance : SectionChooser;
		
		private var holder : Sprite;
		private var data : XMLList;
		
		public static var FIXED_WIDTH : Number;
		public static var FIXED_HEIGHT : Number;

		
		public static function get instance() : SectionChooser {
			if( !_instance ) _instance = new SectionChooser( new SingletonEnforcer( ) );
			return _instance;
		}
		
		
		public function SectionChooser ( enforcer : SingletonEnforcer ) {
			if (!enforcer) trace( "Class must be instantiated using the instance()-method" );
			
			init();
		}
		
		
		private function init() : void {
			var urlloader : URLLoader = new URLLoader();
			urlloader.addEventListener( Event.COMPLETE, completeHandler );
			urlloader.addEventListener( IOErrorEvent.IO_ERROR, errorHandler );
			urlloader.load( new URLRequest( "http://www.threedoubleyou.nl/php/categories_get.php" ) );
		}
		
		
		private function errorHandler(event : IOErrorEvent) : void {
			trace("SectionChooser.errorHandler("+[event]+")");
		}

		
		private function completeHandler( e : Event ) : void {
			data = XMLList( XML( URLLoader( e.currentTarget ).data )['categories']['category'] );
			
			draw();
		}
		
		
		private function draw():void {
/*			var n : int = 0;
			var xml : XML;
			var item : ClickableText;
			var title : Title;
			var sendbutton : CMSButtonWhite;

			holder = new Sprite();
			addChild( holder );
			
			visible = false;
			alpha = 0;

			title = new Title();
			title.txt.text = "Categories:";
			holder.addChild( title );

			for each ( xml in data ) {
				item = new ClickableText( StringUtil.convertToTitleCase( xml ) );
				item.id = xml.@id;
				item.y = 60 + ( n++ * item.height );
				holder.addChild( item );
			}
			
			sendbutton = new CMSButtonWhite( "OK", StageAlign.RIGHT, 0, 10 );
			sendbutton.addEventListener( MouseEvent.CLICK, sendHandler );
			holder.addChild( sendbutton );
			
			holder.x = -( holder.width * .5 );
			holder.y = -( holder.height * .5 ); */
		}
		
		
		private function sendHandler(event : MouseEvent) : void {
		}

		
		public function show() : void {
			var t : Timer = new Timer( 500 );
			t.addEventListener(TimerEvent.TIMER, timerHandler );
			t.start();
			
			FIXED_WIDTH = holder.width + 36;
			FIXED_HEIGHT = holder.height + 36;
			
			//resizeTo( FIXED_WIDTH, FIXED_HEIGHT );
		}
		
		
		private function timerHandler(event : TimerEvent) : void {
			var t : Timer = Timer( event.currentTarget );
			t.removeEventListener(TimerEvent.TIMER, timerHandler );
			t.reset();
			t.stop();
		}
	}
}

class SingletonEnforcer {}